package com.dmz.proxy.config;

import com.dmz.proxy.util.SecurityValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    
    private final SecurityValidator securityValidator;
    
    public GlobalExceptionHandler(SecurityValidator securityValidator) {
        this.securityValidator = securityValidator;
    }
    
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e, HttpServletRequest request) {
        log.error("Global exception handler caught error for request: {}", request.getRequestURI(), e);
        
        String errorMessage = "An unexpected error occurred";
        String safeMessage = securityValidator.escapeHtml(errorMessage);
        String jsonResponse = String.format("{\"error\":\"%s\",\"status\":%d}", safeMessage, 
                HttpStatus.INTERNAL_SERVER_ERROR.value());
        
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .header("X-Content-Type-Options", "nosniff")
                .contentType(org.springframework.http.MediaType.APPLICATION_JSON)
                .body(jsonResponse);
    }
}